package ljl.alg.jianzhioffer.round3.easy;

public class _29_spiralOrder {

    public int[] spiralOrder(int[][] matrix) {
        int rows = matrix.length;
        if (rows == 0) return new int[0];
        int cols = matrix[0].length;
        int[] res = new int[rows * cols];
        int resi = 0;
        int left = 0, right = cols - 1, top = 0, bottom = rows - 1;

        while (left <= right && top <= bottom) {
            for (int i = left; i <= right ; i++) {
                res[resi++] = matrix[top][i];
            }
            if (top < bottom) {
                for (int i = top + 1; i <= bottom ; i++) {
                    res[resi++] = matrix[i][right];
                }
                if (right > left) {
                    for (int i = right - 1; i >= left ; i--) {
                        res[resi++] = matrix[bottom][i];
                    }
                    for (int i = bottom - 1; i > top ; i--) {
                        res[resi++] = matrix[i][left];
                    }
                }

            }
            left++;
            right--;
            top++;
            bottom--;
        }
        return res;
    }
}
